<template>
	<view class="container" style="position: relative;">
		<!-- 顶部宣传图 -->
		<view class="banner" style="width:100%;height:240rpx;overflow-y: hidden;position: sticky;top: 0;z-index: 1;">
			<image class="" src="../../static/image/supermarket/top.png" mode="aspectFill"
				style="width: 100%; height: 100%;border-radius: 20rpx;">
			</image>
		</view>
		<!-- 垂直选项卡 -->
		<view class="content">
			<uv-vtabs :chain="chain" :list="tabList" :barItemBadgeStyle="{right:'20px',top:'12px'}"
				:bar-item-active-line-style="{background: '#fff'}" barWidth="160rpx"
				:barItemActiveStyle="{fontWeight:'700',color:'#EE3F4D'}" :barItemStyle="{borderRadius:'10rpx'}"
				barBgColor="#f5f5f5" keyName="categoryName" @change="changeTab">
				<uv-vtabs-item v-if="goodTotal!=='0'" class="code">
					<view v-for="(item2,index2) in goodsList" :key="index2" class="margin-left-xs"
						style="margin-top: 13px;width: 100%;">
						<view class="flex-row" style="position: relative;" @click="toDetail(item2.id)">
							<image :src="imgURL+item2.indexImg" style="width: 140rpx; height: 140rpx;"
								mode="aspectFill">.
							</image>
							<view class="margin-left-xs">
								<view class="text-df text-bold " style="margin-bottom: 10rpx;">
									{{item2.productName}}
								</view>
								<view class="text-sm flex-row " style="margin-bottom: 10rpx;">
									<text class="margin-right-sm">线上库存: {{item2.inventory}}</text>
									<text>销量: {{item2.salesVolume}}</text>
								</view>
								<view class="flex-row-bt">
									<text class="text-lg text-bold theme-color">￥{{item2.monovalent}}</text>
								</view>
								<view class="flex-row" style="position: absolute;right:8%;top:78rpx;"
									@click.native.stop="addPruduct(index2)">
									<uv-icon v-show="!item2.num" name="plus-circle-fill" color="#EE3F4D" size="30">
									</uv-icon>
									<view style="height: 30rpx;width: 28rpx;border-radius: 50%;text-align: center;">
										<uv-badge v-show="item2.num" :max="item2.inventory" absolute="true"
											:value="item2.num" :offset="[0,8]" type="info"></uv-badge>
									</view>

								</view>
							</view>

						</view>
					</view>
					<view class="text-low text-sm padding-tb-sm" style="height: 500rpx;text-align: center;">
					</view>
					<!-- 筛选卡 -->
					<!-- <view class="flex-row-bt text-bold" style="height:70rpx;margin-top: 12rpx;">
						<text class="text-df theme-color margin-left-lg margin-top-xs">综合</text>
						<view style="margin-right:-14px">
							<filter-shop :current="current" :list="shopselect.list"
								v-on:shopselect_change="shopselect_change"></filter-shop>
						</view>
					</view> -->
				</uv-vtabs-item>
				<uv-vtabs-item v-if="goodTotal=='0'">
					<!-- <view>1323232</view> -->
					<view class="text-low text-sm padding-tb-sm" style="height: 300rpx;text-align: center;">
						我是有底线的~
					</view>
				</uv-vtabs-item>
			</uv-vtabs>
		</view>
		<!-- 底部悬浮购物车 -->
		<view class="flex-row-bt bg-white padding-left-sm"
			style="height:85rpx;border:1px solid #eaeaea;position:fixed;bottom:10rpx;width:80%;border-radius:100rpx;margin-left:10%;z-index:2;">
			<view class="flex-row" @click="openPop()">
				<view class="iconfont icon-gouwuche"
					style="line-height: 36rpx; font-size: 50rpx;color:#EE3F4D;font-weight:700"></view>
				<view class="text-bold" style="vertical-align: bottom;display: flex;">
					<view style="align-items: flex-end;display: flex;flex-direction: row;">
						<text style="font-size:20rpx;">￥</text>
						<uv-loading-icon :show="isLoadingTotal" size="14"></uv-loading-icon>
						<text v-show="!isLoadingTotal">{{ordersList.total}}</text>
					</view>

					<!-- <uv-icon name="arrow-up" size="14" top="6"></uv-icon> -->
				</view>
			</view>
			<view class="theme-bg-color text-white" @click="toOrders()"
				style="width:210rpx;border-radius:90rpx;height:85rpx;line-height:85rpx;text-align:center">去结算</view>
		</view>
		<!-- 购物车弹出层 -->
		<uv-popup ref="popup" mode="bottom" zIndex="1" :closeable="true" :safeAreaInsetTop="true"
			:overlayStyle="{'touch-action':'none'}">
			<view class=" border-radius " style="background-color: #fff;height: fit-content;margin-bottom: 100rpx;margin-top: 30rpx;height: 600rpx;overflow-y: scroll;
			overscroll-behavior: none; ">
				<view class="flex-row-bt margin-bottom-xs padding-lr-sm">
					<view class="text-low text-sm">下单后1-2天送货，急需请提前下单！</view>
					<view class="flex-row">
						<uv-icon name="trash" size="18" class="margin-right-xs" color="#8E8E8E">
						</uv-icon>
						<text class="text-low text-sm" @click="clearNull()">清空</text>
					</view>
				</view>
				<view class="padding-lr-sm padding-tb-sm" v-for="(item,index) in ordersList.list" :key="index">
					<view class="flex-row margin-bottom-xs">
						<!-- 商品图片 -->
						<image :src="imgURL+item.indexImg" mode="aspectFill" class=" margin-right-sm"
							style="width: 150rpx;height: 150rpx;"></image>
						<!-- 内容 -->
						<view class="" style="height: 100%;width: 100%;position: relative;">
							<view class="flex-row-bt text-lg text-bold">
								<view>{{item.productName}}</view>
								<view class="theme-color">￥{{item.monovalent}}</view>
							</view>
							<view style="position: absolute;top: 100rpx;right: 0;">
								<uv-number-box v-model="item.num" :max="item.inventory" :min="0" @change="changeNum">
									<template v-slot:minus>
										<view class="minus">
											<uv-icon name="minus" size="14"
												@click="updateNum(index,'minus',item.productName)">
											</uv-icon>
										</view>
									</template>
									<template v-slot:input>
										<text style="width: 40rpx;text-align: center;" class="input">
											{{item.num}}
										</text>
									</template>
									<template v-slot:plus>
										<view class="plus">
											<uv-icon name="plus" size="14"
												@click="updateNum(index,'plus',item.productName)">
											</uv-icon>
										</view>
									</template>
								</uv-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uv-popup>
	</view>
	<!-- 接口请求加载动画 -->
	<loading></loading>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		computed,
		nextTick
	} from 'vue';
	import {
		imgURL,
		imgURL3
	} from '../../api/request';
	import {
		getCategory,
		getProductByCategory
	} from "../../api/supermarket/supermarket"
	import {
		onLoad,
		onPullDownRefresh
	} from "@dcloudio/uni-app"
	import store from '../../store/login';
	// 纵向选项卡
	const tabList = ref([])
	const chain = ref(false)
	const tabIndex = ref(0)

	// 请求商品列表参数
	const selectProductMsg = ref({
		categoryId: null,
		current: 1,
		size: 10
	})
	// 商品列表
	const goodTotal = ref(0)
	const goodsList = ref([])
	// 购物车商品
	const isLoadingTotal = ref(false)
	const ordersList = reactive({
		total: 0,
		list: []
	})
	// 单个商品信息
	const productOneMsg = ref({
		id: '',
		indexImg: '',
		productName: '',
		inventory: '',
		monovalent: '',
		num: 1
	})
	// 购物车弹出层
	const popup = ref(null)
	const addMsg = ref({
		index: null,
		num: null,
		type: null,
		productName: null
	})
	onLoad(async () => {
		// 获取所有类别
		await getCategories()

	})

	// 获取所有类别
	const getCategories = () => {
		getCategory().then(res => {
			if (res.code == 200) {
				tabList.value = [...res.data]
				selectProductMsg.value.categoryId = tabList.value[0].id
				// 根据类别id查询商品
				getProducts()
			}
		})
	}
	// 根据类别id查询商品
	const getProducts = () => {
		getProductByCategory(selectProductMsg.value).then(res => {
			console.log(res.data)
			goodsList.value = [...res.data.list]
			goodTotal.value = res.data.total
		})
	}
	// 纵向tab切换
	const changeTab = (index : number) => {
		tabIndex.value = index;
		selectProductMsg.value.categoryId = tabList.value[index].id
		// 根据类别id查询商品
		getProducts()
	}
	// 加入购物车
	const addPruduct = async (index : number) => {
		// 如果购物车中存在该商品
		let result = ordersList.list.some(item => item.id === goodsList.value[index].id)
		if (result) {
			// 把购物车中的该商品数量+1
			ordersList.list.forEach(item2 => {
				if (item2.id === goodsList.value[index].id) {
					console.log('977492')
					item2.num += 1
					goodsList.value[index].num += 1
				}
			})
			getTotal()
		} else {
			// 不存在则重新添加上去
			productOneMsg.value.id = goodsList.value[index].id
			productOneMsg.value.indexImg = goodsList.value[index].indexImg
			productOneMsg.value.productName = goodsList.value[index].productName
			productOneMsg.value.monovalent = goodsList.value[index].monovalent
			productOneMsg.value.inventory = goodsList.value[index].inventory
			// productOneMsg.value.num = 1
			ordersList.list.push(JSON.parse(JSON.stringify(productOneMsg.value)))
			goodsList.value[index].num = 1
			getTotal()
		}
	}

	// 结算金额
	const getTotal = async () => {
		isLoadingTotal.value = true
		ordersList.total = 0
		for (let i = 0; i < ordersList.list.length; i++) {
			let c = ordersList.list[i].num
			let b = ordersList.total + (c * Number(ordersList.list[i].monovalent))
			ordersList.total = b
		}
		isLoadingTotal.value = false
	}
	// 去详情
	const toDetail = (id : number) => {
		uni.navigateTo({
			url: '/pages/supermarket/detail?id=' + id
		})
	}
	// 查看购物车
	const openPop = () => {
		if (ordersList.total !== 0) {
			popup.value.open()
		}

	}
	// 购物车弹窗改变商品数量
	const changeNum = (e) => {
		console.log(e.value)
		console.log('1111')
		if (e.value == 0) {
			ordersList.list.splice(addMsg.value.index, 1)
			goodsList.value.forEach(item => {
				if (item.productName == addMsg.value.productName) {
					item.num = 0
				}
			})
			getTotal()
			if (ordersList.total == 0) {
				popup.value.close()
			}
		} else {
			ordersList.list[addMsg.value.index].num = e.value
			goodsList.value.forEach(item => {
				if (item.productName == addMsg.value.productName) {
					item.num = e.value
				}
			})
			getTotal()
		}

	}
	const updateNum = (index, type, productName) => {
		addMsg.value.index = index
		addMsg.value.type = type
		addMsg.value.productName = productName
		console.log(addMsg.value)
	}
	// 清空购物车
	const clearNull = () => {
		uni.showModal({
			title: '提示',
			content: '确认要清空购物车吗？',
			success: function (res) {
				if (res.confirm) {
					ordersList.list = []
					ordersList.total = 0
					popup.value.close()
					nextTick(() => {
						getProducts()
					})
				}
				else {
					uni.showToast({
						title: '取消清空',
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	}
	// 去结算
	const toOrders = () => {
		if (ordersList.list.length !== 0) {
			if (uni.getStorageSync('token')) {
				uni.setStorageSync('orders', ordersList.list)
				uni.navigateTo({
					url: '/pages/supermarket/orders'
				})
			} else {
				store.loginTip()
			}
		} else {
			uni.showToast({
				title: '您还未添加商品',
				icon: 'none',
				duration: 2000
			});
		}

	}
	// 下拉刷新
	onPullDownRefresh(() => {
		selectProductMsg.value.current++
		// 根据类别id查询商品
		getProducts()
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.container {
		padding: 0 2%;
		height: 100vh;
		overflow-y: hidden;

		::-webkit-scrollbar {
			display: none;
			width: 0;
			height: 0;
			color: transparent;
		}
	}

	.content {
		margin-top: 10rpx;
	}

	.minus {
		width: 24px;
		height: 24px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.input {
		padding: 0 10px;
	}

	.plus {
		width: 24px;
		height: 24px;
		background-color: #FF0000;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		color: #fff;
	}
</style>